import os
import time

from Files.models import File
from Util import verify_token, back_failed, back_success


def upload(request):
    res = verify_token(request)
    if not res:
        return back_failed("登录状态失效，请重新登录")
    else:
        try:
            filetype = request.POST.get("type")
            email = res["email"]
            file = request.FILES.get('file', None)
            if not email:
                return back_failed("参数错误")
            if not file:
                return back_failed("参数错误")
            if not filetype:
                return back_failed("参数错误")
            # 时间文件名
            filename = str(int(time.time()))
            # 根据类型设置后缀
            if filetype == "images":
                filename = filename + ".png"
            if filetype == "font":
                filename = filename + ".ttf"
            # 路径：主机+文件名
            # 写入主机
            destination = open(os.path.join("assets/" + str(filetype), filename), "wb+")
            for chunk in file.chunks():
                destination.write(chunk)
            destination.close()
            # 写入数据库
            f = File.objects.create(
                email=email,
                path="assets/" + str(filetype) + "/" + filename,
                filetype=filetype,
                name=file.name
            )
            return back_success({
                "id": f.id,
                "email": f.email,
                "path": f.path,
                "filetype": f.filetype,
                "name": f.name,
            })
        except Exception as e:
            return back_failed("API异常"+str(e))


def get_files(request):
    res = verify_token(request)
    if not res:
        return back_failed("登录状态失效，请重新登录")
    else:
        try:
            email = res["email"]
            filetype = request.POST.get("type")
            if not email:
                return back_failed("参数错误")
            if not filetype:
                return back_failed("参数错误")
            files = File.objects.filter(email=email, filetype=filetype)
            json = []
            for f in files:
                json.append({
                    "path": f.path,
                    "filename": f.name,
                    "id": str(f.id),
                })
            return back_success(json)
        except Exception as e:
            return back_failed("API异常"+str(e))


def delete_file(request):
    try:
        id = request.POST.get("id")
        if not id:
            return back_failed("参数错误")
        f = File.objects.get(id=id)
        if "default_background.png" in f.path:
            return back_failed("默认文件不可删除")
        if "default.ttf" in f.path:
            return back_failed("默认文件不可删除")
        if "default1.ttf" in f.path:
            return back_failed("默认文件不可删除")
        f.delete()
        os.remove(f.path)  # 删除images,font
        return back_success("删除成功")
    except Exception as e:
        return back_failed("API异常"+str(e))